﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace Com.Charence.PassManager.Common
{
    public enum QRQuality
    {
        Low,
        Medium,
        High
    }

    public class QRGenerator
    {
        public static Image Generate(string content, QRQuality quality)
        {
            Stream stream = null;

            var url = string.Format("http://chart.apis.google.com/chart?cht=qr&chld={2}|{3}&chs={0}x{0}&chl={1}", 160, HttpUtility.UrlEncode(content), quality.ToString()[0], 4);

            try
            {
                HttpWebRequest fileReq = (HttpWebRequest)HttpWebRequest.Create(url);

                HttpWebResponse fileResp = (HttpWebResponse)fileReq.GetResponse();

                if (fileReq.ContentLength > 0)
                    fileResp.ContentLength = fileReq.ContentLength;

                stream = fileResp.GetResponseStream();

                var image = Image.FromStream(stream);
                return image;
            }
            finally
            {
                if (stream != null)
                {
                    stream.Close();
                }
            }
        }
    }
}
